package com.zrb.discover;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.zrb.discover.adapter.FundAdapter;
import com.zrb.mobile.BaseLazyFragment;
import com.zrb.mobile.R;
import com.zrb.mobile.adapter.model.DiscoverDtos;
import com.zrb.mobile.adapter.model.Dynamic_CardDto;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.zrb.mobile.ui.CustomloadingView;
import com.zrb.mobile.ui.ListViewEx;
import com.zrb.mobile.ui.PullToRefreshListViewEx;
import com.zrb.mobile.ui.onLoadMoreListener;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.TimeUtil;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

 

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class UserCard_IntentTabFragment extends BaseLazyFragment implements onLoadMoreListener
{
	public static final String TITLE = "title";
	public static final String URLID = "urlId";
	private String mTitle = "Defaut Value";
	private String mUrlId;
	private ListViewEx mListView;
	// private TextView mTextView;
	private List<String> mDatas = new ArrayList<String>();
	boolean isFirstIn = true;
	
	List<Dynamic_CardDto> curDtos;
/* 
	//private News_ContentAdapter mAdapter;*/
	private boolean isFrist=true;
	FundAdapter mFundAdapter;
	CustomloadingView loadinview;
	private String url;
	int currentPage;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		if (getArguments() != null) {
			mTitle = getArguments().getString(TITLE);
			mUrlId= getArguments().getString(URLID);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
	{
		View view;
		//if(mTitle=="11") 
		{
	  	   view = inflater.inflate(R.layout.usercard_fragment_tab, container, false);
		  mListView = (ListViewEx) view.findViewById(R.id.id_stickynavlayout_innerscrollview);
		  loadinview= (CustomloadingView) view.findViewById(R.id.commonloading);
		// mTextView = (TextView) view.findViewById(R.id.id_info);
		// mTextView.setText(mTitle);
 
		
	   /*	  mAdapter = new News_ContentAdapter(this.getActivity());
		  mListView.setAdapter(mAdapter);*/
		}
	/*	else
			view = inflater.inflate(R.layout.no_content, container, false);*/
		return view;

	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
 		super.onActivityCreated(savedInstanceState);
 		
 		mListView.setPagesize(10);
		// Set a listener to be invoked when the list should be refreshed.
 	/*	mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {

				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(CommonUtil.getcurTime(getActivity()));
				currentPage = 1;
				postDelayed(new Runnable() {
					@Override
					public void run() {
						loadUserFundData(-1,true);
					}
				} ,500);
			}
		});*/
 		
 		mFundAdapter = new FundAdapter(UserCard_IntentTabFragment.this.getActivity());
  		mListView.setAdapter(mFundAdapter);
  		 mListView.setOnLoadMoreListener(this);
  	 
	}
	
	private void postDelayed(Runnable curRunnable,long delay){
		if( this.getActivity()==null) return;
		
		UserCardDetailActivity tmpFrag = (UserCardDetailActivity) this.getActivity();
		if (tmpFrag != null)
			tmpFrag.getHandler().postDelayed(curRunnable,delay);
	}
	
/*	@Override
	public void onResume() {
		super.onResume();
		if (this.getUserVisibleHint())
			firstLoad();
	}*/

	@Override
	public void onFirstUserVisible() {
		if (isFirstIn) {
			isFirstIn = false;
 			postDelayed(new Runnable() {
				@Override
				public void run() {
					//mListView.setRefreshing(true);
					currentPage=1;
					loadUserFundData(-1, true) ;
				}
			} ,2500);
		}
	}
	
	@Override
	public void OnLoadMoreEvent() {
		// TODO Auto-generated method stub
		currentPage++;
		postDelayed(new Runnable() {
			@Override
			public void run() {
				loadUserFundData(mFundAdapter.getMinId(), false);
			}
		}, 400);

	}
	
	long mTempTime=0;

	private void addTimeLine() {
		for (int index = 0; index < curDtos.size(); index++) {
			Dynamic_CardDto tempDiscoverDto = curDtos.get(index);
  			long time = tempDiscoverDto.createTime;

			if (!TimeUtil.isSameDayOfMillis(time, mTempTime)) {
				tempDiscoverDto.showTime=true;
				mTempTime = time;
			} else {
				tempDiscoverDto.showTime = false;
			}
 		}
	}
	
	
	ZrbRestClient mZrbRestClient;
	private void loadUserFundData(long maxId, final boolean isreflesh) {
 
		RequestParams param = new RequestParams();
 		param.put("limit", 10);
		param.put("uid", mUrlId);
		if (-1 != maxId) {
			param.put("maxId",maxId);
		}
  
		String url = "intention/listByUser?" + param.toString();
		if(mZrbRestClient==null){
			mZrbRestClient=new ZrbRestClient(this.getActivity());
		}
		mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			 
				CommonUtil.showToast(arg0, UserCard_IntentTabFragment.this.getActivity());
				if (currentPage > 1)
					mListView.hideloading();
			 	else
			 		loadinview.Hide();//.onRefreshComplete(); 
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String results = new String(arg2);
				if (currentPage > 1)
					mListView.hideloading();
		 		else
		 			loadinview.Hide(); 
				
				 
				try {
					Gson gson = new Gson();
					DiscoverDtos fundJson = gson.fromJson(results,
							DiscoverDtos.class);
					if (fundJson.res == 1) {

						if (fundJson.data != null && fundJson.data.size() > 0) {
							addTimeLine();
							mFundAdapter.setDatas(curDtos);
							mFundAdapter.notifyDataSetChanged();
						} else {
							//completeLoad();
							CommonUtil.showToast(String.format("暂无%1$s信息~~",currentPage == 0 ? "" : "更多"),
									 UserCard_IntentTabFragment.this.getActivity());
						}

					} else
						CommonUtil.showToast(fundJson.msg,  UserCard_IntentTabFragment.this.getActivity());
				} catch (Exception e) {
					CommonUtil.showToast(R.string.error_serverdata_loadfail, UserCard_IntentTabFragment.this.getActivity());
				}
			}
		});
		mZrbRestClient.sessionGet(url);
	}
	
	

	public static UserCard_IntentTabFragment newInstance(String title,String uId,List<Dynamic_CardDto> tmpDtos)
	{
		UserCard_IntentTabFragment tabFragment = new UserCard_IntentTabFragment();
		Bundle bundle = new Bundle();
		bundle.putString(TITLE, title);
		bundle.putString(URLID, uId);
		tabFragment.setArguments(bundle);
		tabFragment.curDtos=tmpDtos;
		return tabFragment;
	}

}
